package red.uec.sms;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;
import java.util.Date;

@Data
@Slf4j
public class SmsClient {
    private String baseUrl;
    private String accountSid;
    private String authToken;
    private String appId;

    /**
     * 请求验证码
     * @param phone
     */
    public void sendCode(String phone, String code) {
        String timestamp = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Accept", "application/json");
        httpHeaders.add("Content-Type", "application/json;charset=utf-8");
        httpHeaders.add("Authorization", getAuthorization(timestamp));

        SmsBody smsBody = new SmsBody();
        smsBody.setAppId(appId);
        smsBody.setTemplateId("103488");
        smsBody.setTo(phone);
        smsBody.setDatas(new Object[]{code, "2分钟"});

        HttpEntity<SmsBody> httpEntity = new HttpEntity(smsBody, httpHeaders);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(getFullUrl(timestamp), HttpMethod.POST, httpEntity, String.class);
        log.info("调用短信验证码接口结果：{}", response);
        /*if(!"000000".equals(response.getBody().get("statusCode"))){
            throw new RuntimeException("系统繁忙，请稍候再试！");
        }*/
        /*String code = getCode();
        HashMap<String, Object> result = restAPI.sendTemplateSMS(phone, "103488", new String[] { code, "5分钟" });
        log.info("调用短信验证码接口结果：{}", result);
        if(!"000000".equals(result.get("statusCode"))){
            throw new RuntimeException("系统繁忙，请稍候再试！");
        }*/
    }

    private String getSigParameter(String timestamp){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(accountSid).append(authToken).append(timestamp);
        return new DigestUtils(MessageDigestAlgorithms.MD5).digestAsHex(stringBuilder.toString()).toUpperCase();
    }

    private String getFullUrl(String timestamp){
        String pattern = "{0}/2013-12-26/Accounts/{1}/SMS/TemplateSMS?sig={2}";
        return MessageFormat.format(pattern, baseUrl, accountSid, getSigParameter(timestamp));
    }

    private String getAuthorization(String timestamp){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(accountSid).append(":").append(timestamp);
        return new Base64().encodeAsString(stringBuilder.toString().getBytes());
    }
}
